package com.wgy.day41JDBC.执行DQL语句;

import java.sql.*;

/*
account表 执行DQL语句(返回值的 结果集):查询表中的所有记录 select * from account
*/
public class Demo07JDBC {
    public static void main(String[] args) {
        Connection conn=null;
        Statement stmt=null;
        ResultSet rs=null;

        try {//1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.定义sql
            String sql="select * from account ";
            //3.获取connection对象
            conn = DriverManager.getConnection("jdbc:mysql:///db3","root","root");
            //4.获取执行sql的对象statement
            stmt = conn.createStatement();
            //5.执行sql,接收返回值结果
            rs = stmt.executeQuery(sql);//resultSet:结果集
            //6.处理结果
            //6.1让结果集的游标向下移动一行,
            // 循环判断当前行是否有数据,有就获取
           while(rs.next()) {
               //6.2获取数据
               int id = rs.getInt(1);
               String name = rs.getString("name");
               double balance = rs.getDouble("balance");
               System.out.println(id+"---"+name+"---"+balance);
           }


        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }  //7.释放资源
        finally{
            // stmt.close();
            //避免空指针异常
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

            if(stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }


    }
}
